<?php
/**
 * 销售物料店铺冻结Lib类
 * @author xiayuanjun@shopex.cn
 * @version 1.0
 */
class material_sales_material_shop_freeze{

     function __construct(){
        $this->_salesMaterialShopFreezeObj = app::get('material')->model('sales_material_shop_freeze');
     }

    /**
     *
     * 增加销售物料店铺级别冻结
     * @param String $shop_id
     * @param Int $sm_id
     * @param Int $num
     * @return Boolean
     */
    public function freeze($shop_id, $sm_id, $num){
        //如果该销售物料没有店铺冻结记录，新增一条
        $shopBnFreezeInfo = $this->_salesMaterialShopFreezeObj->getList('sm_id', array('sm_id'=>$sm_id, 'shop_id'=>$shop_id), 0, -1);
        if(!$shopBnFreezeInfo){
            $tmpData = array('sm_id'=>$sm_id, 'shop_id'=>$shop_id, 'shop_freeze'=>0);
            $this->_salesMaterialShopFreezeObj->insert($tmpData);
        }

        $shopFreeze = "shop_freeze=IFNULL(shop_freeze,0)+".$num;

        $sql = "UPDATE sdb_material_sales_material_shop_freeze SET ".$shopFreeze." WHERE sm_id=".$sm_id." AND shop_id = '".$shop_id."'";
        return $this->_salesMaterialShopFreezeObj->db->exec($sql);
    }


    /**
     *
     * 释放销售物料店铺级别冻结
     * @param String $shop_id
     * @param Int $sm_id
     * @param int $num
     * @return Boolean
     */
    public function unfreeze($shop_id, $sm_id, $num){
        $shopFreeze = " shop_freeze=IF((CAST(shop_freeze AS SIGNED)-$num)>0,shop_freeze-$num,0)";

        $sql = "UPDATE sdb_material_sales_material_shop_freeze SET ".$shopFreeze." WHERE sm_id=".$sm_id." AND shop_id = '".$shop_id."'";
        return $this->_salesMaterialShopFreezeObj->db->exec($sql);
    }
    
    /**
     * 手动重新计算指定的单个销售物料对应的店铺冻结
     * 
     * @param String $shop_id
     * @param Int $product_id
     * @return Boolean
     */
    public function update_sales_material_shop_freeze($shop_id, $sm_id)
    {
        #先初始化货品对应店铺的冻结数量
        $sql    = "UPDATE sdb_material_sales_material_shop_freeze SET shop_freeze=0 WHERE sm_id=". $sm_id ." AND shop_id='". $shop_id ."'";
        $result    = $this->_salesMaterialShopFreezeObj->db->exec($sql);
        if(!$result)
        {
            return 'error';
        }
        
        #计算o2o门店未确认收货的订单[注：o2o门店订单收货后才释放店铺冻结数量]
        $o2o_count_num    = 0;
        if(app::get('o2o')->is_installed())
        {
            $o2o_corp_ids   = array();
            $corpObj        = app::get('ome')->model('dly_corp');
            $corp_info      = $corpObj->getList('corp_id', array('d_type'=>2));
            foreach ($corp_info as $key => $val)
            {
                $o2o_corp_ids[]    = $val['corp_id'];
            }
            
            $sql        = "SELECT o.order_id, o.order_bn, o.process_status, o.confirm, j.obj_id, j.obj_type, j.quantity 
                           FROM sdb_ome_order_objects AS j LEFT JOIN sdb_ome_orders AS o ON j.order_id=o.order_id 
                           WHERE o.process_status='splited' AND o.ship_status='0' AND o.status='active' 
                           AND o.shop_id='". $shop_id ."' AND j.goods_id=".$sm_id ." AND o.logi_id in(". implode(',', $o2o_corp_ids) .")";
            $dataList    = $this->_salesMaterialShopFreezeObj->db->select($sql);
            
            if($dataList)
            {
                foreach ($dataList as $key => $val)
                {
                    #获取订单上基础物料信息_过滤掉删除的货品
                    $num    = 0;
                    $sql_item    = "SELECT item_id, product_id, nums, sendnum, item_type FROM sdb_ome_order_items 
                                    WHERE order_id=". $val['order_id'] ." AND obj_id=". $val['obj_id'] ." AND `delete`='false'";
                    $itemRow     = $this->_salesMaterialShopFreezeObj->db->selectrow($sql_item);
                    if(empty($itemRow))
                    {
                        continue;
                    }
                    
                    #销售物料剩余未拆分的数量
                    $diff_num       = intval($itemRow['nums'] - $itemRow['sendnum']);
                    
                    $num    = intval($diff_num / ($itemRow['nums'] / $val['quantity']));
                    if($num)
                    {
                        $o2o_count_num    += $num;#总店铺冻结数量
                    }
                }
            }
        }
        
        #设置店铺冻结数量
        $sql        = "SELECT o.order_id, o.order_bn, o.process_status, o.confirm, j.obj_id, j.obj_type, j.quantity 
                       FROM sdb_ome_order_objects AS j LEFT JOIN sdb_ome_orders AS o ON j.order_id=o.order_id 
                       WHERE o.process_status in ('unconfirmed', 'is_retrial', 'is_declare', 'splitting') AND o.ship_status in('0', '2') 
                       AND o.status='active' AND o.shop_id='". $shop_id ."' AND j.goods_id=".$sm_id;
        $dataList    = $this->_salesMaterialShopFreezeObj->db->select($sql);
        if(empty($dataList))
        {
            #[更新]销售物料店铺冻结
            $sql           = "UPDATE sdb_material_sales_material_shop_freeze SET shop_freeze=". $o2o_count_num ." 
                              WHERE sm_id=". $sm_id ." AND shop_id='". $shop_id ."'";
            $result        = $this->_salesMaterialShopFreezeObj->db->exec($sql);
            if(!$result)
            {
                return 'error';
            }
            
            return $o2o_count_num;
        }
        
        $count_num    = 0;
        foreach ($dataList as $key => $val)
        {
            #订单部分拆分_但未确认状态
            if($val['confirm'] != 'N' && $val['process_status'] != 'splitting')
            {
                continue;//跳过
            }
            
            #获取订单上基础物料信息_过滤掉删除的货品
            $num    = 0;
            $sql_item    = "SELECT item_id, product_id, nums, sendnum, item_type FROM sdb_ome_order_items 
                            WHERE order_id=". $val['order_id'] ." AND obj_id=". $val['obj_id'] ." AND `delete`='false'";
            $itemRow     = $this->_salesMaterialShopFreezeObj->db->selectrow($sql_item);
            if(empty($itemRow))
            {
                continue;
            }
            
            #销售物料剩余未拆分的数量
            if($val['process_status'] == 'splitting')
            {
                #部分拆分时_直接减去发货单上货品数量
                $dly_sql        = "SELECT SUM(number) AS num FROM `sdb_ome_delivery_items_detail` AS did 
                                   JOIN `sdb_ome_delivery` AS d ON d.delivery_id=did.delivery_id 
                                   WHERE did.order_item_id='". $itemRow['item_id'] ."' AND did.product_id='". $itemRow['product_id'] ."' 
                                   AND d.status NOT IN('back', 'cancel', 'return_back') AND d.is_bind='false'";
                $dly_num        = $this->_salesMaterialShopFreezeObj->db->selectrow($dly_sql);
                $diff_num       = intval($itemRow['nums'] - $dly_num['num']);
            }
            else 
            {
                $diff_num       = intval($itemRow['nums'] - $itemRow['sendnum']);
            }
            
            $num    = intval($diff_num / ($itemRow['nums'] / $val['quantity']));
            if($num)
            {
                $count_num    += $num;#总店铺冻结数量
            }
        }
        
        $count_num    = $count_num + $o2o_count_num;#加上O2O店铺冻结数量
        
        #[更新]销售物料店铺冻结
        $sql           = "UPDATE sdb_material_sales_material_shop_freeze SET shop_freeze=". $count_num ." 
                          WHERE sm_id=". $sm_id ." AND shop_id='". $shop_id ."'";
        $result        = $this->_salesMaterialShopFreezeObj->db->exec($sql);
        if(!$result)
        {
            return 'error';
        }
        
        return $count_num;
    }
}
